from django.db import transaction
from rest_framework import permissions

from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import Upload
from .serializers import AdornServiceSerializers, OrderServiceSerializers
from .models import AdornService, OrderService
from .filters import AdornServiceFilter, OrderServiceFilter


# Create your views here.
class OrderServiceViewSet(CustomModelViewSet):
    permission_classes = [permissions.IsAdminUser]
    queryset = OrderService.objects.filter()
    serializer_class = OrderServiceSerializers

    def filter_queryset(self, queryset):
        f = OrderServiceFilter(self.request.GET, queryset=self.queryset)
        return f.qs


class AdornServiceViewSet(CustomModelViewSet):
    '''装修服务'''
    permission_classes = [permissions.IsAdminUser]
    queryset = AdornService.objects.filter()
    serializer_class = AdornServiceSerializers

    def filter_queryset(self, queryset):
        f = AdornServiceFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                # raise_exception 标志，如果存在验证错误，将会抛出 serializers.ValidationError 异常
                if serializer.is_valid(raise_exception=True):
                    file_id = request.data['image']
                    upload = Upload.objects.filter(id=file_id).first()
                    if not upload:
                        return response_error('文件不存在')
                    # 有时您会希望您的视图代码能够在保存实例时注入额外的数据。此额外数据可能包括当前用户,您可以通过在调用 .save() 时包含其他关键字参数来执行此操作
                    serializer.save(image=upload)
                    return response_ok()
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
